package com.szwistar.common.ai;

import com.szwistar.common.algorithm.Base64Util;
import com.szwistar.common.os.FileUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ImageClassify {
    // 使用 JRE 自带的实现
    public static String post(String urlstr, String contentType, String params, String encoding) throws Exception {
        URL url = new URL(urlstr);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(params.getBytes(encoding));
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> headers = connection.getHeaderFields();
        // 遍历所有的响应头字段
        for (String key : headers.keySet()) {
            System.err.println(key + "--->" + headers.get(key));
        }
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        in = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        System.err.println("result:" + result);
        return result;
    }

    public static String post(String url, String accessToken, String params) throws Exception {
        String contentType = "application/x-www-form-urlencoded";
        url = url + "?access_token=" + accessToken;
        String encoding = "UTF-8";
        if (url.contains("nlp")) { encoding = "GBK"; }
        return post(url, contentType, params, encoding);
    }

    /**
     * 图像分类
     */
    public static String imageClassify(String catagory, String imagePath) {
    	// 图片类型及API URL对应表
        Map<String, String> apis = new HashMap<String, String>();
        // 植物
        apis.put("plant", "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant");
        // 花
        apis.put("flower", "https://aip.baidubce.com/rest/2.0/image-classify/v1/flower");
        // 识别果蔬类食材
        apis.put("ingredient", "https://aip.baidubce.com/rest/2.0/image-classify/v1/classify/ingredient");
        // 蔬菜
        apis.put("vegetables2", "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/classification/vegetables2");
        // 动物
        apis.put("animal", "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal");
        // 识别车型
        apis.put("car", "https://aip.baidubce.com/rest/2.0/image-classify/v1/car");

        try {
            // 本地文件路径
            byte[] imgData = FileUtils.readFileAsBytes(new File(imagePath));
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam + "&top_num=" + 5;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            // curl -i -k 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=pG50czoTXEVfkR7RchU1IXWW&client_secret=bsOtLGNqKLlezFgosMspgnuL9PMt78No'
            String accessToken = "24.cfcab1cacd7298bdc187d0a767e8dba4.2592000.1554863058.282335-11543717";

            String result = post(apis.get(catagory), accessToken, param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 测试命令行
   	 * java -jar ImageClassify.jar car 1.jpg
     * @param args
     */
    public static void main(String[] args) {
    	if(args.length < 2) {
            System.out.println("java -jar ImageClassify.jar ingredient tianjiao1.jpg");
            return;
    	}
    	imageClassify(args[0], args[1]);
    }
}
